package com.etalk.crm.serviceImpl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.etalk.crm.client.interfaces.WeChatSendMessageClient;
import com.etalk.crm.dao.*;
import com.etalk.crm.pojo.*;
import com.etalk.crm.service.KcOrdersService;
import com.etalk.crm.service.OrderBooksService;
import com.etalk.crm.service.OrderLogService;
import com.etalk.crm.utils.DateUtil;
import com.etalk.crm.utils.OssGetObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.github.pagehelper.util.StringUtil;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.time.DateFormatUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.math.BigDecimal;
import java.text.ParseException;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author Terwer
 * @date 2018/11/12 18:27
 * @version 1.0
 * @Description 订单
 **/
@Service
public class KcOrdersServiceImpl implements KcOrdersService {
    private static final Logger logger = LogManager.getLogger(KcOrdersServiceImpl.class);

    @Resource
    private PersonMapper personMapper;
    @Resource
    private KcOrdersMapper kcOrdersMapper;
    @Resource
    private LessonsMapper lessonsMapper;
    @Resource
    private OrderBooksService orderBooksService;
    @Resource
    private WeChatSendMessageClient weChatSendMessageClient;
    @Resource
    private KcPackageMapper kcPackageMapper;
    @Resource
    private TextBooksMapper textBooksMapper;
    @Resource
    private OemOrderMapper oemOrderMapper;
    @Resource
    private OrderLogService orderLogService;
    @Resource
    private OrderBooksMapper orderBooksMapper;
    @Resource
    private HttpSession session;

    @Transactional
    @Override
    public boolean addKcOrdersFromActivity(List<String> names, int packageType, KcPackage kcPackage, int activityId, String activityName, int isGift) {
        boolean flag = false;

        // 批量添加订单
        // 批量查询学员信息
        List<Person> personList = personMapper.selectPersonAndOpenIds(names);
        for (String loginName : names) {
            // 学员信息
            Person person = personList.stream().filter(x -> x.getLoginName().equals(loginName)).findFirst().get();
            Integer personId = person.getId();
            int storesId = person.getStoresId();

            // 获取该学员所有微信的openId
            List<String> openIds = personList.stream().filter(x -> x.getLoginName().equals(loginName)).map(y -> y.getOpenId()).collect(Collectors.toList());

            KcOrders record = new KcOrders();
            record.setBuyTime(DateUtil.getCurrentDatetime());
            record.setState(1);
            KcOrders ko;
            String id = "PO" + DateUtil.getToday("yyyyMMdd") + (int) (Math.random() * 10) + (int) (Math.random() * 10) + (int) (Math.random() * 10) + (int) (Math.random() * 10);
            while (StringUtil.isEmpty(record.getId())) {
                ko = kcOrdersMapper.selectByOrderId(id);
                if (ko == null || StringUtil.isEmpty(ko.getId())) {
                    record.setId(id);
                } else {
                    id = "PO" + DateUtil.getToday("yyyyMMdd") + (int) (Math.random() * 10) + (int) (Math.random() * 10) + (int) (Math.random() * 10) + (int) (Math.random() * 10);
                }

            }

            record.setLoginName(loginName);
            record.setPersonId(personId);
            record.setStoresId(storesId);
            record.setClassifyId(kcPackage.getClassifyId());
            record.setPackageTypeFlag(kcPackage.getTypeFlag());
            record.setLearnedClass(0);
            record.setEverydayclass(kcPackage.getClassCount());
            record.setValid(kcPackage.getValid());
            record.setPackageId(kcPackage.getId());
            record.setPackageName(kcPackage.getName());
            record.setPrice(new BigDecimal(kcPackage.getPrice()));
            record.setSalePrice(new BigDecimal(kcPackage.getPrice()));

            if (kcPackage.getClassNum() == null) {
                record.setClassNum(1);
            } else {
                record.setClassNum(kcPackage.getClassNum());
            }
            if (kcPackage.getClassLong() == null) {
                record.setClassLong(17);
            } else {
                record.setClassLong(kcPackage.getClassLong());
            }
            record.setPayMoney(record.getSalePrice());
            record.setPayType("0");
            record.setOldcount(0);
            record.setOldbuycount(0);
            record.setIntroduce(kcPackage.getIntroduce());
            record.setBuycount(kcPackage.getLessonCount());
            record.setGift(null == kcPackage.getGift() ? 0 : kcPackage.getGift());
            record.setLessonCount(kcPackage.getLessonCount() + (null == kcPackage.getGift() ? 0 : kcPackage.getGift()));
            record.setClassifyLevel(kcPackage.getClassifyLevel());
            if (null == record.getLearnedClass()) {
                record.setLearnedClass(0);
            }
            if (null == record.getEverydayclass()) {
                record.setEverydayclass(0);
            }
            if (StringUtil.isEmpty(record.getRemark())) {
                record.setRemark("");
            }
            if (null == record.getGift()) {
                record.setGift(0);
            }
            if (null == record.getLessonCount()) {
                record.setLessonCount(record.getGift() + record.getLessonCount());
            }

            // 即时生效
            if (packageType == 1) {
                record.setStartDate(new Date());
            } else {
                Date lastoutDate = kcOrdersMapper.getLastOutdate(personId);
                if (null != lastoutDate) {
                    record.setStartDate(lastoutDate);
                } else {
                    record.setStartDate(new Date());
                }
            }
            record.setSurplusValid(DateUtil.format(DateUtil.addDateToDay(record.getStartDate(), (record.getValid() + 1))).trim());

            OrderBooks ob = new OrderBooks();
            ob.setOrderId(record.getId());
            ob.setPersonId(record.getPersonId());
            ob.setComplete(0);
            ob.setTextbooksId(0);
            ob.setStoresId(record.getStoresId());
            ob.setCurrentpage("p0");
            ob.setPageindex(0);
            ob.setFinish(0);
            ob.setSequence(1);
            ob.setRegister("admin");
            boolean result = orderBooksService.addOrderBooks(ob);
            if (result) {
                logger.info("活动赠送匹配教材成功");
                record.setTextbookId(ob.getId());
            } else {
                logger.info("活动赠送匹配教材失败");
            }

            record.setCreater("admin");
            int num = kcOrdersMapper.insertOrder(record);
            if (num > 0) {
                flag = true;
                logger.info("-----------------订单添加成功-------------------");

                // 给赠送成功的学员发送通知
                for (String openId : openIds) {
                    if (null != openId) {
                        logger.info("给赠送成功的学员发送通知");
                        weChatSendMessageClient.sendEventGiftMessage(openId, loginName, activityName, kcPackage.getName());
                    }
                }
            } else {
                logger.error("-----------------添加订单失败-------------------");
            }
        }
        return flag;
    }

    /**
     * 查询学员信息卡显示的订单信息
     * @param personId 学员id
     * @param pageNum 页码
     * @param pageSize 页记录数
     * @return 结果
     */
    @Override
    public PageInfo<KcOrders> searchOrderListByPersonId(Integer personId, int pageNum, int pageSize){
        if (org.springframework.util.StringUtils.isEmpty(pageNum)){
            pageNum=1;
        }
        PageHelper.startPage(pageNum, pageSize);
        List<KcOrders> list=kcOrdersMapper.selectOrderListByPersonId(personId);
        BigDecimal classConsumptionRate;
        BigDecimal dateConsumptionRate;
        long toDay=System.currentTimeMillis();
        long buyTimes;
        for (KcOrders kcOrders:list){
            if (kcOrders.getPayMoney()==null){
                kcOrders.setPayMoney(BigDecimal.ZERO);
            }
            buyTimes=kcOrders.getBuyTime().getTime();
            if (kcOrders.getStrLearnedClass().compareTo(BigDecimal.ZERO)>0) {
                classConsumptionRate = kcOrders.getStrLearnedClass().divide(BigDecimal.valueOf(kcOrders.getLessonCount()), 2, BigDecimal.ROUND_HALF_UP);
                try {
                    long surplusDateTimestamp=DateUtils.parseDate(kcOrders.getSurplusValid(), "yyyy-MM-dd").getTime();
                    long diffTimestamp=surplusDateTimestamp-buyTimes;
                    if (diffTimestamp==0){
                        diffTimestamp=1;
                    }
                    dateConsumptionRate = BigDecimal.valueOf(toDay-buyTimes).divide(BigDecimal.valueOf(diffTimestamp), 2, BigDecimal.ROUND_HALF_UP);
                } catch (ParseException e) {
                    logger.error("订单[{}]到期日期[{}]转换错误[{}]", kcOrders.getId(), kcOrders.getSurplusValid(), e.getMessage(), e);
                    dateConsumptionRate = BigDecimal.ONE;
                }
                if (dateConsumptionRate.compareTo(BigDecimal.ZERO)==0){
                    dateConsumptionRate=BigDecimal.valueOf(0.01);
                }
                kcOrders.setSpeedProgress(classConsumptionRate.divide(dateConsumptionRate, 2, BigDecimal.ROUND_HALF_UP).multiply(BigDecimal.valueOf(100)).intValue());
            }else {
                kcOrders.setSpeedProgress(0);
            }
        }
        return new PageInfo<>(list);
    }

    /**
     * 查询学员信息的订单信息
     * @param personId 学员id
     * @param pageNum 页码
     * @param pageSize 页记录数
     * @return 结果
     */
    @Override
    public PageInfo<KcOrders> searchAvailableOrderListByPersonId(Integer personId, int pageNum, int pageSize){
        if (org.springframework.util.StringUtils.isEmpty(pageNum)){
            pageNum=1;
        }
        PageHelper.startPage(pageNum, pageSize);
        List<KcOrders> list=kcOrdersMapper.selectAvailableOrderListByPersonId(personId);
        for (KcOrders kcOrders:list){
            if (kcOrders.getPayMoney()==null){
                kcOrders.setPayMoney(BigDecimal.ZERO);
            }
        }
        return new PageInfo<>(list);
    }

    @Override
    public int addKcOrdersByDemo(int kcPackageId, Integer personId, int storesId) {
        KcOrders record = new KcOrders();
    	KcPackage kPackage = kcPackageMapper.getPackegeInfoById(kcPackageId);
    	record.setBuyTime(DateUtil.getCurrentDatetime());
        record.setStartDate(DateUtil.getCurrentDate());
    	record.setState(1);
    	KcOrders ko;
    	String id="PO"+DateUtil.getToday("yyyyMMdd")+(int)(Math.random()*10)+(int)(Math.random()*10)+(int)(Math.random()*10)+(int)(Math.random()*10);
    	while (StringUtil.isEmpty(record.getId())) {
			ko=kcOrdersMapper.selectByOrderId(id);
			if (ko==null || StringUtil.isEmpty(ko.getId())) {
				record.setId(id);
			}else {
				id="PO"+DateUtil.getToday("yyyyMMdd")+(int)(Math.random()*10)+(int)(Math.random()*10)+(int)(Math.random()*10)+(int)(Math.random()*10);
			}

		}

    	//record.setLoginName(loginName);
    	record.setPersonId(personId);
    	record.setStoresId(storesId);
    	record.setClassifyId(kPackage.getClassifyId());
    	record.setPackageTypeFlag(kPackage.getTypeFlag());
    	record.setLearnedClass(0);
    	record.setEverydayclass(kPackage.getClassCount());
    	record.setValid(kPackage.getValid());
    	record.setPackageId(kPackage.getId());
    	record.setPackageName(kPackage.getName());
    	record.setPrice(new BigDecimal(kPackage.getPrice()));
    	record.setSalePrice(new BigDecimal(kPackage.getPrice()));

    	if(kPackage.getClassNum()==null){
    		record.setClassNum(1);
		}else{
			record.setClassNum(kPackage.getClassNum());
		}
    	if(kPackage.getClassLong()==null){
    		record.setClassLong(17);
		}else{
			record.setClassLong(kPackage.getClassLong());
		}
    	record.setPayMoney(record.getSalePrice());
		record.setPayType("0");
		record.setOldcount(0);
		record.setOldbuycount(0);
		record.setIntroduce(kPackage.getIntroduce());
    	record.setBuycount(kPackage.getLessonCount());
		record.setGift(kPackage.getGift() == null?0:kPackage.getGift());
		record.setLessonCount(kPackage.getLessonCount()+(kPackage.getGift() == null?0:kPackage.getGift()));
		record.setClassifyLevel(kPackage.getClassifyLevel());
    	if(record.getLearnedClass() == null){
    		record.setLearnedClass(0);
    	}
    	if(record.getEverydayclass() == null){
    		record.setEverydayclass(0);
    	}
    	if(StringUtil.isEmpty(record.getSurplusValid())){
    		record.setSurplusValid(DateUtil.format(DateUtil.addDateToDay(DateUtil.getCurrentDate(), (record.getValid()+1))).trim());
    	}
    	if (StringUtil.isEmpty(record.getRemark())) {
    		record.setRemark("");
		}
    	if(record.getGift() == null){
    		record.setGift(0);
    	}
    	if(record.getLessonCount() == null){
    		record.setLessonCount(record.getGift()+record.getLessonCount());
    	}

		OrderBooks ob=new OrderBooks();
		ob.setOrderId(record.getId());
		ob.setPersonId(record.getPersonId());
		ob.setComplete(0);
		ob.setTextbooksId(110);
		ob.setStoresId(record.getStoresId());

	    Textbooks textbooks=textBooksMapper.selectByTextbooksId(110);
	    if (textbooks!=null && StringUtil.isNotEmpty(textbooks.getAddress())) {
		    String strCfg= OssGetObject.getCfgJson(textbooks.getAddress().endsWith("/")?(textbooks.getAddress()+"cfg.json"):(textbooks.getAddress()+"/cfg.json"));
		    if (StringUtil.isNotEmpty(strCfg)) {
			    JSONArray jsonCfg = JSON.parseArray(strCfg);
			    String currentPage = jsonCfg.getJSONObject(0).getString("n");
			    ob.setCurrentpage(currentPage);
		    }
	    }
	    if (StringUtil.isEmpty(ob.getCurrentpage())) {
		    ob.setCurrentpage("p0");
	    }
		ob.setPageindex(0);
		ob.setFinish(0);
		ob.setSequence(1);
		ob.setRegister("admin");
		boolean num=orderBooksService.addOrderBooks(ob);
		if(num){
			logger.info("注册用户自动匹配教材成功");
			record.setTextbookId(ob.getId());
		}else{
			logger.info("注册用户自动匹配教材失败");
		}

    	record.setCreater("admin");
    	int result = kcOrdersMapper.insertOrder(record);
		if (result > 0) {
			logger.info("-----------------订单添加成功-------------------");
			if(storesId==27){

		    	//Stores stores = storesMapper.selectStoreInfoById(storesId);
    			//判断OEM机构课程节数是否用完
        		List<OemOrder> list = oemOrderMapper.selectByStoresId(storesId);
        		int classcount=0;
        		if(list!=null && list.size()>0){
                    for (OemOrder oemOrder : list) {
                        classcount += oemOrder.getRemainingClass();
                    }
        		}
        		classcount-=record.getLessonCount();
    			if(classcount<0){
    				logger.error("-------------------对不起，套餐总课时数已超出购买的剩余课时数,剩余课时数："+(classcount-record.getLessonCount())+"----------------------");
    	    		return -2;
    			}else if(record.getState()==1){
    				//OEM减去订单中的总数
    				List<OemOrder> listOEMOrder=new ArrayList<OemOrder>();
    	    		if(list!=null && list.size()>0){
    	    			int classCount=record.getLessonCount();
                        for (OemOrder oemOrder : list) {
                            if (oemOrder.getRemainingClass() > 0) {
                                if (oemOrder.getRemainingClass() - classCount >= 0) {
                                    oemOrder.setRemainingClass(oemOrder.getRemainingClass() - classCount);
                                    classCount = 0;
                                } else {
                                    classCount -= oemOrder.getRemainingClass();
                                    oemOrder.setRemainingClass(0);
                                }
                                listOEMOrder.add(oemOrder);
                                if (classCount <= 0) {
                                    break;
                                }
                            }
                        }
    	    		}
    	    		if(listOEMOrder.size()>0){
    					int onum=0;
                        for (OemOrder oemOrder : listOEMOrder) {
                            onum = oemOrderMapper.updateByPrimaryKeySelective(oemOrder);
                        }
    					if(onum>0){
    						logger.info("----黄金屋课时售出减少成功-----");
    					}else{
    						logger.info("----黄金屋课时售出减少失败-----");
    					}
    		    	}
    			}
			}
		}else {
			logger.error("-----------------添加订单失败-------------------");
		}
    	return result;
    }

    /**
     * 修改订单购买时间
     * @param orderId 订单id
     * @param newBuyTime 新的购买时间
     * @return 记录数
     */
    @Override
    public int modifyOrderBuyTime(String orderId, Date newBuyTime){
        KcOrders oldKcOrders = kcOrdersMapper.selectByOrderId(orderId);

        // 修改订单信息
        int result = kcOrdersMapper.updateBuyTime(orderId, newBuyTime);

        // 修改购买时间日志
        if (!DateUtils.isSameDay(oldKcOrders.getBuyTime(), newBuyTime)) {
            OrderLog startDateOrderLog = new OrderLog();
            startDateOrderLog.setOrderId(orderId);
            startDateOrderLog.setPersonId(oldKcOrders.getPersonId());
            startDateOrderLog.setRecorder(session.getAttribute("loginname").toString());
            startDateOrderLog.setState(OrderLogType.CHANGE_BUY_TIME.getValue());
            startDateOrderLog.setDesc("修改了" + oldKcOrders.getPackageName() + "购买时间,原购买时间 " + DateFormatUtils.format(oldKcOrders.getBuyTime(),"yyyy-MM-dd HH:mm:ss") + " 变更为 " + DateFormatUtils.format(newBuyTime,"yyyy-MM-dd HH:mm:ss"));
            orderLogService.addOrderLog(startDateOrderLog);
        }
        return result;
    }

    /**
     * 废除或终止订单
     * @param personId 学员id
     * @param orderId 订单id
     * @param remark 废除或终止订单说明
     * @return 记录数
     */
    @Override
    public int abolishOrderById(int personId,String orderId,String remark){
        KcOrders kcOrders=kcOrdersMapper.selectByOrderId(orderId);
        if (kcOrders.getState()>0) {
            int num = lessonsMapper.selectClassCountByOrderId(orderId);
            if (num>0){
                return -1;
            }
            String remarks=String.format("---------------订单终止-----------------<br>操作人：%s<br>操作时间：%s<br>终止原因：%s",session.getAttribute("loginname").toString(),DateUtil.getToday("yyyy年MM月dd日 HH:mm:ss"),remark);
            if (StringUtils.isNotEmpty(kcOrders.getRemark())){
                remarks=String.format("<br>%s",remarks);
            }
            num=kcOrdersMapper.updateStateByOrderId(orderId,personId,remarks);
            if (num>0) {
                OrderLog endOrderLog = new OrderLog();
                endOrderLog.setOrderId(kcOrders.getId());
                endOrderLog.setPersonId(kcOrders.getPersonId());
                endOrderLog.setRecorder(session.getAttribute("loginname").toString());
                endOrderLog.setState(OrderLogType.STOP_ORDER.getValue());
                endOrderLog.setDesc("终止订单:" + kcOrders.getPackageName() + ",终止原因:" + remark);
                orderLogService.addOrderLog(endOrderLog);
            }
            return num;
        }
        return 0;
    }

    /**
     * 查询订单信息
     * @param orderId 订单id
     * @return 订单信息
     */
    @Override
    public KcOrders searchSplitGiftOrderById(String orderId){
        KcOrders kcOrders = kcOrdersMapper.selectOrderSplitGiftByOrderId(orderId);
        kcOrders.setSurplus(BigDecimal.valueOf(kcOrders.getLessonCount()).subtract(kcOrders.getStrLearnedClass()));
        kcOrders.setMaxSplitNum(kcOrders.getSurplus().setScale(0,BigDecimal.ROUND_DOWN).intValue());
        return kcOrders;
    }

    /**
     * 提交拆分订单数据
     * @param orderId 订单id
     * @param splitNum 拆分数量
     * @param materialId 教材id
     * @param materialPage 教材页码
     * @param materialPageName 教材页码名称
     * @param personId 赠送用户id
     * @param loginName 赠送用户登录名
     * @return
     */
    @Transactional(rollbackFor=Exception.class)
    @Override
    public int addSplitGiftKcOrder(String orderId, int splitNum, int materialId, int materialPage, String materialPageName, int personId, String loginName){
        KcOrders kcOrders=kcOrdersMapper.selectByOrderId(orderId);
        kcOrders.setStrLearnedClass(BigDecimal.valueOf(kcOrders.getLearnedClass()).divide(BigDecimal.valueOf(100),2,BigDecimal.ROUND_HALF_UP));
        if (BigDecimal.valueOf(kcOrders.getLessonCount()).subtract(kcOrders.getStrLearnedClass()).compareTo(BigDecimal.valueOf(splitNum))>=0){
            int lessonCount=kcOrders.getLessonCount();
            int buyCount=kcOrders.getBuycount();
            int gift=kcOrders.getGift();
            if (gift>=splitNum){
                gift-=splitNum;
            }else {
                buyCount-=Math.abs(gift-splitNum);
                gift=0;
            }
            lessonCount-=splitNum;
            int num=kcOrdersMapper.updateClassCountById(orderId,lessonCount,buyCount,gift,String.format("原币%s，拆分%s，%s。",kcOrders.getLessonCount(),splitNum,kcOrders.getPersonId()==personId?"学其它":("赠送给"+loginName)));
            if(num>0){
                OrderLog endOrderLog = new OrderLog();
                endOrderLog.setOrderId(orderId);
                endOrderLog.setPersonId(kcOrders.getPersonId());
                endOrderLog.setRecorder(session.getAttribute("loginname").toString());
                endOrderLog.setState(OrderLogType.SPLIT_GIFT.getValue());
                endOrderLog.setDesc("拆分订单:" + kcOrders.getPackageName() + ",拆分数量:" + splitNum+",被赠送人:"+loginName);
                orderLogService.addOrderLog(endOrderLog);

                String newOrderId="";
                while (StringUtil.isEmpty(newOrderId)) {
                    newOrderId = "PO" + DateUtil.getToday("yyyyMMdd") + (int) (Math.random() * 10) + (int) (Math.random() * 10) + (int) (Math.random() * 10) + (int) (Math.random() * 10);
                    if (kcOrdersMapper.countById(newOrderId)>0) {
                        newOrderId="";
                    }
                }
                OrderBooks orderBooks=new OrderBooks();
                orderBooks.setOrderId(newOrderId);
                orderBooks.setPersonId(personId);
                orderBooks.setComplete(0);
                orderBooks.setTextbooksId(materialId);
                orderBooks.setStoresId(kcOrders.getStoresId());
                orderBooks.setCurrentpage(materialPageName);
                orderBooks.setPageindex(materialPage);
                orderBooks.setFinish(0);
                orderBooks.setSequence(1);
                orderBooks.setRegister("admin");
                boolean isTrue=orderBooksService.addOrderBooks(orderBooks);
                if (!isTrue){
                    return 0;
                }
                num=kcOrdersMapper.insertKcOrderByOrderId(orderId,newOrderId,splitNum,orderBooks.getId(),personId,loginName,String.format("%s拆分所得。",kcOrders.getId()));
                if (num>0){
                    endOrderLog = new OrderLog();
                    endOrderLog.setOrderId(newOrderId);
                    endOrderLog.setPersonId(personId);
                    endOrderLog.setRecorder(session.getAttribute("loginname").toString());
                    endOrderLog.setState(OrderLogType.ADD_SPLIT_GIFT.getValue());
                    endOrderLog.setDesc("添加拆分订单:" + kcOrders.getPackageName() + ",获得数量:" + splitNum+",赠送人:"+kcOrders.getLoginName()+",拆分订单id:"+orderId);
                    orderLogService.addOrderLog(endOrderLog);
                }
                return num;
            }
        }
        return 0;
    }

    /**
     * 查询正式有效订单
     * @param record 查询条件
     * @param pageNum 页码
     * @param pageSize 页记录数
     * @return
     */
    @Override
    public PageInfo<FormalOrderInfo> searchFormalOrderInfoListByPage(FormalOrderInfo record, Integer pageNum, Integer pageSize){
        if (pageNum==null ||  pageNum<1){
            pageNum = 1;
        }
        if (pageSize == null || pageSize < 1){
            pageSize=50;
        }
        int roleId=Integer.parseInt(session.getAttribute("roleId").toString());
        int sscId = Integer.parseInt(session.getAttribute("userid").toString());
        if (roleId==1) {
            sscId = 0;
        }
        PageHelper.startPage(pageNum, pageSize);
        if (record!=null && StringUtils.isNotEmpty(record.getSearchKey())){
            record.setSearchKey(record.getSearchKey().trim());
            record.setListKey(new ArrayList<>());
            String[] arrayKey=record.getSearchKey().trim().split(" ");
            for (String key:arrayKey){
                if (!"".equals(key)){
                    record.getListKey().add(key);
                }
            }
        }
        List<FormalOrderInfo> list= kcOrdersMapper.selectFormalOrderInfoBySscId(sscId,record);

        return new PageInfo<>(list);
    }

    /**
     * 查询ssc名下学员正式有效订单在学教材
     * @return
     */
    @Override
    public List<FormalOrderInfo> searchFormalTextbookList(){
        Integer roleId=Integer.parseInt(session.getAttribute("roleId").toString());
        Integer sscId = Integer.parseInt(session.getAttribute("userid").toString());
        if (roleId==1) {
            sscId = 0;
        }
        return kcOrdersMapper.selectFormalTextbookBySscId(sscId);
    }
    /**
     * 切换下本教材
     * @param listOrderBookId 订单教材关联id
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public Map<String,Object> modifyOrderNextMaterial(List<Integer> listOrderBookId){
        Map<String,Object> resultMap=new HashMap<>(2);
        List<Textbooks> list=orderBooksMapper.selectOrderBookById(listOrderBookId);
        if (list==null || list.size()==0){
            resultMap.put("status", 0);
            resultMap.put("errMsg", "没有查到教材记录");
            return resultMap;
        }
        int successNum=0,errorNum=0;
        for (Textbooks record:list) {
            String enName=record.getEnname();
            if (StringUtils.isNotEmpty(enName) && enName.contains("-")) {
                String[] arrayName = enName.split("-");
                try {
                    if (arrayName.length == 3) {
                        if ("1".equals(arrayName[2])) {
                            enName = arrayName[0] + "-" + arrayName[1] + "-2";
                        } else if ("2".equals(arrayName[2])) {
                            enName = arrayName[0] + "-" + (Integer.parseInt(arrayName[1]) + 1) + "-1";
                        }
                    } else if (arrayName.length == 2) {
                        enName = arrayName[0] + "-" + (Integer.parseInt(arrayName[1]) + 1);
                    }
                }catch (Exception e){
                    logger.info("教材编号不规范，无法切换教材："+e.getMessage());
                    errorNum+=1;
                    continue;
                }

                //查询下一本教材id
                Integer textbookId;
                try {
                    textbookId = textBooksMapper.selectIdByEnName(enName);
                }catch (Exception e){
                    logger.info("教材编号重复，无法切换教材："+e.getMessage());
                    errorNum+=1;
                    continue;
                }
                if (textbookId == null) {
                    errorNum+=1;
                } else {
                    int num = orderBooksMapper.updateOrderBookById(record.getOrderBookId(), textbookId);
                    if (num > 0) {
                        successNum+=1;
                        OrderLog orderLog=new OrderLog();
                        orderLog.setOrderId(record.getOrderId());
                        orderLog.setPersonId(record.getPersonId());
                        orderLog.setRecorder(session.getAttribute("loginname").toString());
                        orderLog.setState(OrderLogType.CHANGE_TEXTBOOK.getValue());
                        orderLog.setDesc("更换下一本教材:订单："+record.getOrderId()+"，教材id："+textbookId+"，教材编号："+enName);
                        orderLogService.addOrderLog(orderLog);
                    } else {
                        errorNum+=1;
                    }
                }
            }else {
                errorNum+=1;
            }
        }
        resultMap.put("status",1);
        resultMap.put("successNum",successNum);
        resultMap.put("errorNum",errorNum);

        return resultMap;
    }
}
